import logging

from google.appengine.api.datastore import Key
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.http import HttpResponse
from django.http import HttpResponseRedirect

from django.core.urlresolvers import reverse
from player.forms import PlayerRegisterForm
from player.models import Player

from match.forms import MatchNewForm

def register(request):    
    
    form = PlayerRegisterForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            newpl = Player(first_name=request.POST.get('first_name'),last_name = request.POST.get('last_name'),email=request.POST.get('email'))
            newpl.set_password(request.POST.get('pass1'))
            newpl.put()
            request.session['current_player'] = newpl
            request.session.save()
            return HttpResponseRedirect(reverse('player_home'))

    return render_to_response('player/register.html',{"form":form},RequestContext(request))
    


def home(request):    
#    if isinstance(request.session.get('current_player'),Key):
#        request.session['current_player'] = Player.get(request.session.get('current_player'))        
    firsthome = request.session.get('current_player').firsthome
    request.session['current_player'].setFirstHome(False)
    request.session.save()
    matches_player = request.session.get('current_player').matches #im player
    
    matches = request.session.get('current_player').my_matches #owner
    return render_to_response('player/player_home.html',locals(),context_instance=RequestContext(request))
    
def new_match(request):
    from match.models import Match
    form = MatchNewForm(request.POST or None)
    if request.method == 'POST':        
        new_match = Match.create(request.POST,request.session.get('current_player'))
        
    return render_to_response('player/new_match.html',{"form":form},context_instance=RequestContext(request))
    
def logout(request):
    request.session.clear()
    return HttpResponseRedirect(reverse('home'))

def search(request):
    from django.utils import simplejson    
    q = request.GET.get('q')
    
    q2 = q
    q2 = q[0:len(q)-1] + chr(int(ord(q[-1]))+1)

    qr = Player.all().filter('first_name >=',q).filter('first_name <',q2)
    loaded = []
    result = []

    for r in qr:        
        result.append(dict(name=r.first_name or "",email=r.email))
        loaded.append(r.key().id())
    qr2 = Player.all().filter('email >=',q).filter('email <',q2)
    
    for r in qr2:         
        if not r.key().id() in loaded:
            result.append(dict(name=r.first_name or "",email=r.email))
            loaded.append(r.key().id())
    
    return HttpResponse(simplejson.dumps(result), mimetype='application/json')
    














 